package com.cy.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cy.common.Constant;
import com.cy.entity.User;
import com.cy.service.UserService;
import com.cy.util.CommunityUtil;
import com.cy.util.CookieUtil;
import com.cy.util.MailClient;
import com.cy.util.RedisKeyUtil;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: cy
 * @Date: 2022/01/01/14:53
 * @Description:
 */
@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private UserService userService;

    @Resource
    private Producer kaptchaProducer;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 跳转到注册页面
     * @return
     */
    @GetMapping("register")
    public String getRegisterPage(){
        return "/site/register";
    }

    /**
     * 跳转到登录页面
     * @return
     */
    @GetMapping("login")
    public String getLoginPage(){
        return "/site/login";
    }


    @PostMapping(value = "/register")
    public String register(Model model, User user){
        Map<String, Object> map = userService.register(user);
        if(map == null || map.isEmpty()){
            //注册成功
            model.addAttribute("msg", "注册成功，我们已经向您的邮箱发送一封激活邮件，请尽快激活！");
            model.addAttribute("target", "/home/index");
            return "/site/operate-result";
        }else {
            //注册失败发送错误提示
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return "/site/register";
        }
    }

    // http://localhost:8080/community/activation/101/code

    /**
     * 激活账号
     * @param model
     * @param userId    用户id
     * @param code      激活码
     * @return
     */
    @GetMapping("activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId") String userId, @PathVariable("code") String code){
        int result = userService.activation(userId, code);
        if(result == Constant.ACTIVATION_SUCCESS){
            //激活成功
            model.addAttribute("msg", "激活成功,你的账号已经可以正常使用！");
            model.addAttribute("target", "/login");
        }else if(result == Constant.ACTIVATION_REPEAT){
            model.addAttribute("msg", "无效操作，此账号已经激活过！");
            model.addAttribute("target", "/index");
        }else {
            model.addAttribute("msg", "激活失败，您提供的激活码不正确！");
            model.addAttribute("target", "/index");
        }
        return "/site/operate-result";
    }


    /**
     * 生成验证码
     * @param response
     */
    @GetMapping(path = "/kaptcha")
    public void getKaptcha(HttpServletRequest request, HttpServletResponse response/*, HttpSession session*/){
        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        //将验证码存入session，下次访问时将验证码带回服务端
//        session.setAttribute("kaptcha", text);

        //验证码的归属
        String kaptchaOwner = CommunityUtil.generateUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);
        //将验证码存入redis中
        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(redisKey, text, 60, TimeUnit.SECONDS);

        //将图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            logger.error("响应验证码失败：" + e.getMessage());
        }
    }


    /**
     * 登录逻辑
     * @param username
     * @param password
     * @param code
     * @param rememberme
     * @param model
     * @param response
     * @return
     */
    @PostMapping(path = "/login")
    public String login(String username, String password, String code, boolean rememberme,
                        Model model/*, HttpSession session*/, HttpServletResponse response
                        , @CookieValue("kaptchaOwner") String kaptchaOwner
                        ) {
        // 检查验证码
//        String kaptcha = (String) session.getAttribute("kaptcha");
        String kaptcha = null;
        if(StrUtil.isNotBlank(kaptchaOwner)){
            kaptcha = (String) redisTemplate.opsForValue().get(RedisKeyUtil.getKaptchaKey(kaptchaOwner));

        }
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码不正确!");
            return "/site/login";
        }

        // 检查账号,密码
        int expiredSeconds = rememberme ? Constant.REMEMBER_EXPIRED_SECONDS : Constant.DEFUALT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contextPath);        //设置cookie有效范围
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);         //向客户端发送cookie
            return "redirect:/home/index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }
    }


    /**
     * 退出登录
     * @param ticket   登录凭证
     * @return
     */
    @GetMapping(path = "/logout")
    public String logout(@CookieValue("ticket") String ticket){
        Boolean flog = userService.logout(ticket);
        if(flog){
            SecurityContextHolder.clearContext();
            return "redirect:/login";
        }
        return "redirect:/logout";
    }



}
